import platform
import subprocess

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.utils import free_port
from seleniumwire.webdriver import Chrome


class _DriverService:
    def __init__(self):
        self._port = free_port()
        self._process = None
        self.start_service()

    @property
    def server_port(self):
        return self._port

    def start_service(self):
        # 驱动地址  # TODO: 更新驱动
        chrome_home = r"C:\Users\Q\AppData\Local\Google\Chrome\Application\chrome.exe"
        cmd = f"{chrome_home} --remote-debugging-port={self.server_port}"
        self._process = subprocess.Popen(cmd)

    def stop_service(self):
        self._process.kill()


# 启动浏览器的配置
class ChromeOptions(Options):
    common_options = [
        "--incognito",  # 隐身模式
        "--disable-gpu",  # 规避可能存在的 bug
        "--headless",
    ]

    linux_options = [
        "--no-sandbox",  # 最高权限运行，linux下允许 root 用户启动
        "--headless",  # 无头模式，可加开浏览器运行速度
    ]

    @property
    def is_linux(self):
        return platform.system().lower() == "linux"

    def __init__(self, server_port=None):
        super().__init__()
        if server_port:
            self.add_experimental_option("debuggerAddress", f"127.0.0.1:{server_port}")

        for i in self.common_options:
            self.add_argument(i)
        if self.is_linux:
            for i in self.linux_options:
                self.add_argument(i)


class ChromeService:
    def __init__(self, service=None):
        self._driver_service = service or _DriverService()
        self._webdriver = Chrome(options=ChromeOptions(server_port=self._driver_service.server_port))

    @property
    def webdriver(self):
        return self._webdriver

    @property
    def driver_service(self):
        return self._driver_service

    def stop_service(self):
        self._driver_service.stop_service()
